<?php
/*获取verify_ticket*/
define('LOGPATH', dirname(__FILE__));
/*官方DEMO文件*/
include_once(dirname(__FILE__) .'/WXlog/wxBizMsgCrypt.php');

/*参数*/
$encodingAesKey = 'sz3U0nKOj3c82XPpjX3Z4G3JUCOzUjkjPGcNQCcQ3Pu'; 
$token          = 'MOpJZPmze5UXiULCYJYYlbOGEYXPdo1P';
$appId          = 'wxe0f593c3d6706d31';
$timeStamp      = empty($_GET['timestamp'])?'':trim($_GET['timestamp']) ;
$nonce          = empty($_GET['nonce'])?'':trim($_GET['nonce']) ;
$msg_sign       = empty($_GET['msg_signature'])?'':trim($_GET['msg_signature']) ;
$encryptMsg     = file_get_contents('php://input');

/*新建类*/
$wxbmc = new WXBizMsgCrypt($token, $encodingAesKey, $appId);

$xml_tree = new DOMDocument();
$xml_tree->loadXML($encryptMsg);
$array_e = $xml_tree->getElementsByTagName('Encrypt');
$encrypt = $array_e->item(0)->nodeValue;

$format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
$from_xml = sprintf($format, $encrypt);
/*收到平台发送消息*/
$msg = '';
$errCode = $wxbmc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
// logResult('/WXlog/formx.log', $errCode);//+
// var_dump($errCode);//+
if($errCode == 0){
    $xml = new DOMDocument();
    $xml->loadXML($msg);
    /*Ticket状态*/
    $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
    $component_verify_ticket = $array_e->item(0)->nodeValue;
    /*Appid状态*/
    $check_a = $xml->getElementsByTagName('AuthorizationCode');
    $check_b = $xml->getElementsByTagName('InfoType');
    $AuthorizationCode = $check_a->item(0)->nodeValue;
    $InfoType = $check_b->item(0)->nodeValue;
    /*判断*/
    if($InfoType=='unauthorized'){
        M('Accredit')->where("authcode = '".$AuthorizationCode."'")->save(array('state'=>0));
        $a = M('Accredit')->getLastSql();
    }
    else if($InfoType=='authorized'){
        M('Accredit')->where("authcode = '".$AuthorizationCode."'")->save(array('state'=>1));
        $a = M('Accredit')->getLastSql();
    }  
    else if($InfoType=='updateauthorized'){
        M('Accredit')->where("authcode = '".$AuthorizationCode."'")->save(array('state'=>2));
        $a = M('Accredit')->getLastSql();
    }
    if($AuthorizationCode&&$InfoType){
        logResult('/WXlog/formx.log', $a);
    }
    else{
        file_put_contents(LOGPATH.'/WXlog/ticket.log', $component_verify_ticket);
        echo 'success';
    }
}

/*写日志*/
function logResult($path,$data){
    file_put_contents(LOGPATH.$path, '['.date('Y-m-d : h:i:sa',time()).']'.$data."\r\n",FILE_APPEND);
}

die();